#ifndef MOVING_SPHERE_H
#define MOVING_SPHERE_H
#include<QVector3D>
#include<hitable.h>
#include<utils.h>
class moving_sphere:public hitable
{
public:
    QVector3D center0,center1;

    float time0,time1;
    float radius;
    material*mat_ptr;
    moving_sphere(){}
    moving_sphere(QVector3D cen0,QVector3D cen1,float t0,float t1,float r,material*m):
        center0(cen0),center1(cen1),time0(t0),time1(t1),radius(r),mat_ptr(m){};
    virtual bool hit(const ray &r, float tmin, float tmax, hit_record &rec) const
    {
        QVector3D oc=r.origin()-center(r.time());
        float a=QVector3D::dotProduct(r.direction(),r.direction());
        float b=QVector3D::dotProduct(oc,r.direction());
        float c=QVector3D::dotProduct(oc,oc)-radius*radius;
        float discriminant=b*b-a*c;
        rec.mat_ptr=mat_ptr;
        if(discriminant>0)
        {
            float temp=(-b-sqrt(b*b-a*c))/a;
            if(temp<tmax&&temp>tmin)
            {
                rec.t=temp;
                rec.p=r.point_at_parameter(rec.t);
                rec.normal=(rec.p-center(r.time()))/radius;
                return true;
            }
            temp=(-b+sqrt(b*b-a*c))/a;
            if(temp<tmax&&temp>tmin)
            {
                rec.t=temp;
                rec.p=r.point_at_parameter(rec.t);
                rec.normal=(rec.p-center(r.time()))/radius;
                return true;
            }

        }
        return false;
    }
    virtual bool bounding_box(float t0,float t1,aabb&box)const{
        aabb box1=aabb(center(t0)-QVector3D(radius,radius,radius),center(t0)+QVector3D(radius,radius,radius));
        aabb box2=aabb(center(t1)-QVector3D(radius,radius,radius),center(t1)+QVector3D(radius,radius,radius));
        box=surrounding_box(box1,box2);
        return true;
    }
    QVector3D center(float time)const
    {
        return center0+((time-time0)/(time1-time0))*(center1-center0);
    }
};





#endif // MOVING_SPHERE_H
